<?php

require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'db_connection.php';

class dao_category {

    //Methods
    public function __construct() {

    }

    public function get_all() {
        $db = new db_connection();
        $con = $db->open_connect();
        
        $query = "SELECT * FROM tblcategories";
        $result = mysqli_query($con, $query)
        or die("Query fail: " . mysqli_error());
        
        $list = array();
        while ($row = mysqli_fetch_array($result)) {
            array_push($list, $row);
        }
        $db->close_connect($con);
        return $list;
    }

    public function save($category_id, $title) {
        $db = new db_connection();
        $con = $db->open_connect();

        if ($category_id == 0) {
            $query = "INSERT INTO tblcategories(Title) VALUES ('" . $title . "')";
        } else {
            $query = "UPDATE tblcategories SET Title = '" . $title . "' WHERE CategoryID = " . $category_id;
        }
        $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());

        $db->close_connect($con);
        return TRUE;
    }

    public function get_by_id($id) {
        $db = new db_connection();
        $con = $db->open_connect();

        $query = "SELECT * FROM tblcategories WHERE CategoryID = " . $id;
        $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());

        $row = mysqli_fetch_array($result);

        $db->close_connect($con);
        return $row;
    }

    public function delete($id) {
        $db = new db_connection();
        $con = $db->open_connect();

        $query = "DELETE FROM tblcategories WHERE CategoryID = " . $id;
        mysqli_query($con, $query) or die("Query fail: " . mysqli_error());

        $db->close_connect($con);
        return TRUE;
    }

    function get_all_categories_by_journal_id($journal_id) {
        $db = new db_connection();
        $con = $db->open_connect();

        $query = "SELECT * FROM tblcategories c JOIN tbl_category_journal cj ON c.CategoryID = cj.CategoryID WHERE cj.JournalID = " . $journal_id;
        $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error());

        $list = array();
        while ($row = mysqli_fetch_array($result)) {
            array_push($list, $row);
        }

        $db->close_connect($con);
        return $list;
    }
    
}
